<template>
  <div class="app-container">
    <el-row :gutter="20" style="height: 40px"></el-row>
    <el-row :gutter="20">
      <el-col :span="16">
        <div class="grid-content">
          <div class="taobao-like">淘宝宝</div>
          <div class="taobao-e">taobaobao</div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="grid-content">
          <el-input
              v-model="input"
              style="width: 240px;height: 55px;"
              placeholder="请输入要搜索的宝贝"
              clearable
              class="rounded-input"
          />
          <el-button type="primary" style="height: 55px" @click="search" class="rounded-search">搜本店</el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 修改为独立滚动布局 -->
    <el-row :gutter="20" class="content-row">
      <!-- 左侧独立滚动区域 -->
      <el-col :span="14" class="scroll-column left-column">
        <el-scrollbar height="calc(100vh - 200px)" @end-reached="loadMore">
          <div class="grid-contents">
            <div class="ke-fu" >
              <el-col :span="3">
                <div style="width: 100%">客服</div>
              </el-col>
              <el-col :span="14">
                <div style="width: 100%;">
                  <p style="font-size: 20px">{{shop.shopName}}</p>
                  <p style="color: #FFA500">
                    <el-icon v-for="n in 5" :key="n" :style="{ color: n <= starCount ? '#FFA500' : '#CCCCCC' }">
                      <StarFilled/>
                    </el-icon>
                    {{ rating }}
                  </p>
                </div>
              </el-col>
              <el-col :span="3">
                <div class="button-container">
                  <el-button type="primary" class="custom-button" @click="gotoshopchat">
                    <el-icon>
                      <ChatDotRound/>
                    </el-icon>
                    客服
                  </el-button>
                </div>
              </el-col>
              <el-col :span="3">
                <div class="button-container">
                  <el-button type="primary" @click="jindian" class="custom-button">
                    <el-icon>
                      <Shop/>
                    </el-icon>
                    进店
                  </el-button>
                </div>
              </el-col>
            </div>
            <div class="image-gallery">
              <div class="image-container">
                <div class="thumbnail-container">
                  <el-scrollbar height="450px" @end-reached="loadMore">
                    <div class="thumbnail-list">
                      <el-image
                          v-for="(item, index) in imageList"
                          :key="index"
                          :src="item.url"
                          class="thumbnail"
                          @click="activeIndex = index"
                          :class="{ active: activeIndex === index }"
                          fit="cover"
                          lazy
                      />
                    </div>
                  </el-scrollbar>
                </div>
                <div class="large-image-container">
                  <el-image
                      v-if="imageList.length > 0"
                      :src="imageList[activeIndex].url"
                      fit="contain"
                      lazy
                      style="width: 100%; height: 100%;"
                  />
                  <div v-else class="empty-state">暂无图片数据</div>
                </div>
              </div>
            </div>
            <div style="font-size: 20px; font-weight: bold;">用户评价</div>
            <div><span>全部</span><span>({{reviews.length}})</span></div>
            <div class="review-list">
              <el-card v-for="(item, index) in reviews" :key="index" shadow="hover">
                <template #header>
                  <div class="card-header">
                    <img
                        :src="item.avatar || 'https://picsum.photos/40/40?random=' + index"
                        class="avatar"
                        alt="用户头像"
                    />
                    <span class="nickname">{{ item.nc || '匿名用户' }}</span>
                    <div class="sku">商品规格：{{ item.sku }}</div>
                    <span class="time">{{ item.time }}</span>
                  </div>

                </template>
                <div class="content_row">
                  <div class="content">{{ item.content }}</div>
                  <div style="padding-left: 20px">
                    <el-button
                        plain
                        :disabled="item.replyContent !== '暂无回复'"
                        @click="item.replyContent === '暂无回复' && addReview(item.id)"
                    >
                      {{ item.replyContent === '暂无回复' ? '回复' : '已回复' }}
                    </el-button>
                    <el-dialog
                        v-model="dialogVisible"
                        width="500"
                        :before-close="handleClose"
                        :modal="false"
                    >
                      <el-input v-model="inputs"></el-input>
                      <el-button @click=goReview>发送</el-button>
                      <el-button @click="dialogVisible = false">取消</el-button>
                    </el-dialog></div>
                </div>
                <div class="contents" v-if="item.replyContent!='暂无回复'">
                  商家回复：{{item.replyContent}}</div>

              </el-card>
            </div>
          </div>
        </el-scrollbar>
      </el-col>

      <!-- 右侧独立滚动区域 -->
      <el-col :span="10" class="scroll-column right-column">
        <div class="right-scroll-wrapper">
          <el-scrollbar height="calc(100vh - 280px)" @end-reached="loadMore">
            <div class="grid-contentss"></div>
            <div>
              <div><h2>{{ product.name }}</h2>
                <div class="price-container">
                  <div class="price-info">
                    <span class="price-after" style="font-size: 15px">券后</span>
                    <span class="price-after" style="font-size: 30px">¥{{ product.priceAfter }}</span>
                    <span class="price-before" style="font-size: 15px">优惠前¥{{ product.priceBefore}}</span>
                    <span class="sales" style="font-size: 15px">已售1万+</span>
                  </div>
                </div>
              </div>
              <div
                  class="product-options"
                  v-for="(specValues, specName) in allSpecs"
                  :key="specName"
              >
                <h3 class="option-title">{{ specName }}</h3>
                <el-radio-group
                    v-model="selectedSpecs[specName]"
                    class="color-options"
                >
                  <el-radio
                      v-for="(item, index) in specValues"
                      :key="index"
                      :label="item.label"
                      class="color-option"
                  >
                    <el-image
                        v-if="item.img"
                        :src="item.img"
                        alt="规格预览"
                        fit="cover"
                        class="color-img"
                    >
                      <template #error>
                        <div class="color-img-placeholder">{{ item.label.charAt(0) }}</div>
                      </template>
                    </el-image>
                    <span class="color-name">{{ item.label }}</span>
                  </el-radio>
                </el-radio-group>
              </div>
              <div class="count_row">
                <div style="color: gray;padding-right: 10px;text-align: center;align-items: center;">数量</div>
                <el-button @click="reduceCount" v-if="count > 1" style="width: 50px;height: 50px;font-size: 30px;">-</el-button>
                <el-button @click="reduceCount" v-else style="width: 50px;height: 50px;font-size: 30px;" disabled>-</el-button>
                <el-input v-model="count" style="width: 50px;text-align: center;align-items: center;"/>
                <el-button @click="addCount" style="width: 50px;height: 50px;font-size: 30px;">+</el-button>
                <div style="color: gray;padding-right: 10px;text-align: center;align-items: center;" v-if="product.count>product.buyEd">有货</div>
                <div style="color: gray;padding-right: 10px;text-align: center;align-items: center;" v-else>无货</div>
              </div>
            </div>
          </el-scrollbar>

          <!-- 固定在底部的操作按钮 -->
          <div class="product-actions">
            <el-button
                type="primary"
                size="large"
                @click="addToCart"
                class="action-btn add-to-cart-btn"
            ><el-icon><ShoppingCartFull/></el-icon>
              加入购物车
            </el-button>
            <el-button
                type="success"
                size="large"
                @click="buyWithCoupon"
                class="action-btn buy-with-coupon-btn"
            >
              领券购买
            </el-button>
            <el-button
                size="large"
                @click="collect"
                :icon="isCollected ? 'el-icon-star-on' : 'el-icon-star-off'"
                class="action-btn collect-btn"
            >
              {{ isCollected ? '已收藏' : '收藏' }}
            </el-button>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue'
import type {ScrollbarDirection} from 'element-plus'
import {ElImage, ElMessage} from 'element-plus'
import {ChatDotRound, Shop, StarFilled, ShoppingCartFull} from '@element-plus/icons-vue'
import axios from 'axios';
import {useRoute,useRouter} from 'vue-router';
import {AuthService} from "../../service/auth";
const authService = new AuthService();
const userId = authService.getUserId();
console.log(userId);
const router = useRouter();
const count = ref(1);
const dialogVisible = ref(false);
const currentReviewId = ref('');
const inputs = ref('');
const route=useRoute();
const shop = ref({
  id: '',
  userId: '',
  logo: '',
  shopName: '',
})
const reviews = ref([]);
const product = ref({
  shopId:'',
  id: '',
  name: '',
  priceBefore: '',
  priceAfter: '',
  img: '',
  buyEd: 0,
  mainImg: '',
  count: 0,
});
const addReview=( reviews  :String )=>{
currentReviewId.value = reviews;
dialogVisible.value = true;
};
const goReview =async () => {
  console.log(input.value);
  const {data} = await axios.post('/api/shop/reviewShop',{
    reviewId:currentReviewId.value,
    productId:product.value.id,
    text:inputs.value,
    userShopId:shop.value.userId,
  });
  if (data>0){
    ElMessage.success('回复成功');
  }
  dialogVisible.value = false;
  doCount();
};
const handleClose = (done) => {
  dialogVisible.value = false;
  done();
};
const allReviews = ref([]);
const doCount=async ()=>{
  console.log("开始查询评论");
  console.log(product.value.id);
  const {data} = await axios.get(`/api/shop/review/list/${product.value.id}`);
  console.log("评论列表");
  reviews.value = data;
  if (data!=null){
    console.log("你好"+data)
  }else {
    console.log("没有数据")
  }
  console.log(reviews.value)
}

const imageList = ref([])
const activeIndex = ref(0)

const loading = ref(true);
const error = ref(false);
const isCollected = ref(false);
const selectedInfo = ref('');
const allSpecs = ref<Record<string, any[]>>({});
const selectedSpecs = ref<Record<string, string>>({});
const spId=ref();

const  doShop = async () => {
  const {data} = await axios.get('/api/shop', {
    params: {
      id: product.value.shopId
    }
  });
  console.log(data);
  shop.value = data;
}
const jindian=()=>{
  router.push(
      {
        name: 'shop',
        params: {
          id: product.value.shopId
        }
      }
  )
}
const reduceCount = () => {
  if (count.value > 1) {
    count.value--;
  }
}
const addCount = () => {
  count.value++;
}
const gotoshopchat=()=>{
  console.log(product.value.shopId);
  router.push(
      {
        name: 'shopChat',
        params: {
          shopId: product.value.shopId
        }
      }
  )
}
const doProduct = async () => {
  loading.value = true;
  error.value = false;
  try {
    const productRes = await axios.get(`/api/product/select/${product.value.id}`);
    console.log('商品基本信息:', productRes.data);
    product.value = productRes.data;
    console.log(product.value.buyEd+'---'+product.value.count)
    if (product.value.img) {
      let imgUrls = [];
      if (Array.isArray(product.value.img)) {
        // 如果是数组，直接使用
        imgUrls = product.value.img;
      }
      imageList.value = imgUrls.map(url => ({url}));
    }

    const specsRes = await axios.post('/api/product/Productspec', {
      productId: product.value.id
    });
    console.log('规格信息原始数据:', specsRes.data);
    const specsData = specsRes.data;

    allSpecs.value = {};
    selectedSpecs.value = {};

    for (const spec of specsData) {
      try {
        console.log(`正在处理规格: ${spec.specName} (ID: ${spec.id})`);

        const specValuesRes = await axios.post('/api/product/ProductspecValue/select', {
          specId: spec.id
        });
        console.log(`规格 ${spec.specName} 的值:`, specValuesRes.data);

        if (!specValuesRes.data || specValuesRes.data.length === 0) {
          console.warn(`规格 ${spec.specName} 没有返回任何值`);
          continue;
        }

        allSpecs.value[spec.specName] = specValuesRes.data.map((specValue: any) => ({
          label: specValue.value || specValue.specName || '默认',
          img: specValue.img || specValue.image || '',
          id: specValue.id
        }));

        if (specValuesRes.data.length > 0) {
          selectedSpecs.value[spec.specName] = specValuesRes.data[0].value || specValuesRes.data[0].name || '默认';
        }
      } catch (specError) {
        console.error(`获取规格 ${spec.name} 的值失败:`, specError);
      }
    }
    console.log('allSpecs键名:', Object.keys(allSpecs.value));
    console.log('最终的allSpecs:', allSpecs.value);
    console.log('最终的selectedSpecs:', selectedSpecs.value);

    if (allSpecs.value['颜色']) {
      console.log('颜色规格存在，值为:', allSpecs.value['颜色']);
    } else {
      console.log('未找到颜色规格');
      const colorKeys = Object.keys(allSpecs.value).filter(key =>
          key.includes('颜色') || key.toLowerCase().includes('color')
      );
      if (colorKeys.length > 0) {
        console.log('可能的颜色规格键名:', colorKeys);
      }
    }
  } catch (err) {
    console.error('获取商品数据失败:', err);
    error.value = true;
    ElMessage.error('获取商品信息失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

const addToCart = async () => {
  selectedInfo.value = Object.entries(selectedSpecs.value as Record<string, string>)
      .map(([specName, specValue]) => `${specName}: ${specValue}`)
      .join(', ');
  const {data} = await axios.post('/api/shopCar/add', {
    count: count.value,
    price: product.value.priceAfter,
    shopId: shop.value.id,
    sku: selectedInfo.value,
    productId: product.value.id,
    userId: userId
  });
  if (data != null) {
    console.log(data)
    console.log(selectedInfo.value)
    ElMessage.success('添加成功');
  } else {
    console.log("555")
  }
  await router.push('/ShopCar')
};

const buyWithCoupon = () => {
  selectedInfo.value = Object.entries(selectedSpecs.value as Record<string, string>)
      .map(([specName, specValue]) => `${specName}: ${specValue}`)
      .join(', ');

  ElMessage.success(`即将领券购买【${product.value.name}】，规格: ${selectedInfo.value}`);
};

const collect = () => {
  isCollected.value = !isCollected.value;
  ElMessage.success(isCollected.value ? '收藏成功' : '取消收藏');
};
import { watch } from 'vue'; // 引入watch

onMounted(async () => {

  spId.value = route.params.spId;
  console.log( spId.value)
  // 初始加载数据
  if (route.params.spId) {
    product.value.id =route.params.spId;
    await loadAllData(); // 统一加载所有数据
  }
  await addRecord()
  // 监听路由参数变化（商品ID变化时触发）
  watch(
      () => route.params.id, // 监听路由中的id参数
      async (newId) => {
        if (newId) {
          product.value.id = newId; // 更新当前商品ID
          await loadAllData(); // 重新加载所有数据
        }
      },
      { immediate: true } // 初始时立即执行一次
  );
});

const addRecord = async () => {
  console.log("店铺id:"+product.value.shopId)
  const { data } = await axios.post('/api/user/record/add', {
    shopId: product.value.shopId,
    userId: userId
  });

};
// 统一加载所有依赖商品ID的数据
const loadAllData = async () => {
    reviews.value = [];
    imageList.value = [];
    await doProduct(); // 加载商品详情
    await doCount();   // 加载评论列表
    await doShop();    // 加载店铺信息
};

const rating = ref(3.6)

const getStarCount = (rating: number) => {
  return Math.ceil(rating);
}

const starCount = ref(getStarCount(rating.value));
const input = ref('')
const num = ref(30)

const search = async () => {
  try {
    const { data } = await axios.get('/api/product/selects/change', {
      params: {
        shopId: product.value.shopId, // 基于当前店铺ID搜索
        name: input.value // 搜索关键词
      }
    });

    // 假设接口返回的是符合条件的商品列表，取第一个匹配商品
    if (data && data.id) {
      await router.push({
        name: 'productMain', // 替换为你的商品详情页路由名称
        params: { spId: data.id } // 传递新商品ID
      });
      window.history.go(0)
    } else {
      ElMessage.error('未找到该商品');
    }
  } catch (err) {
    console.error('搜索失败:', err);
    ElMessage.error('搜索出错，请重试');
  }
};
const loadMore = (direction: ScrollbarDirection) => {
  if (direction === 'bottom') {
    num.value += 5
  }
}
</script>

<style scoped>
.app-container {
  background-color: white;
  display: flex;
  flex-direction: column;
  padding-left: 100px;
  padding-right: 100px;
  padding-top: 30px;
  height:100%;
}

.content-row {
  display: flex;
  background: white;
  gap: 20px;
}

.scroll-column {
  height: calc(100vh - 200px);
}

.left-column {
  flex: 1;
}

.right-column {
  flex: 0 0 calc((100% - 20px) * 10 / 24);
}

.right-scroll-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.right-scroll-wrapper .el-scrollbar {
  flex: 1;
}

.review-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 20px;
  background: white;
}

.review-list .el-card {
  background: white;
  border: 1px solid #ebeef5;
}

.review-list .el-card__header {
  background: white;
}

.review-list .el-card__body {
  background: white;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.nickname {
  font-weight: 600;
  font-size: 14px;
}

.time {
  color: #999;
  font-size: 12px;
  margin-left: auto;
}

.content_row {
  margin: 12px 0;
  line-height: 1.6;
  font-size: 14px;
  color: #303133;
  line-height: 1.6;
  display: flex;
  width: 100%;

}
.content{
  width: 80%;
}

.sku {
  color: #666;
  font-size: 13px;
  padding-top: 8px;
}

.contents{
  font-size: 10px;
  color: #303133;
  line-height: 1.6;
  margin-bottom: 12px;
}
.image-list {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.review-image {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
}

.useful-count {
  padding: 12px 16px;
  color: #909399;
  font-size: 13px;
}

.ke-fu {
  height: 80px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 10px;
  padding: 0 20px;
  background: white;
}

.count_row {
  display: flex;
  gap: 10px;
  margin-left: 20px;
  height: 60px;
  align-items: center;
  background: white;
}

.taobao-like {
  font-family: 'SimilarToTaobao', "Microsoft YaHei", "微软雅黑", sans-serif;
  font-size: 24px;
  font-weight: 600;
  color: #FF4400;
  letter-spacing: -0.5px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.taobao-e {
  font-family: 'SimilarToTaobao', "Microsoft YaHei", "微软雅黑", sans-serif;
  font-size: 14px;
  font-weight: 600;
  color: #FF4400;
  letter-spacing: -0.5px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.grid-content {
  font-family: "Microsoft YaHei", Arial, sans-serif;
  height: 55px;
  border-radius: 4px;
  min-height: 36px;
  background: white;
}

.grid-contents {
  height: 100%;
  font-family: "Microsoft YaHei", Arial, sans-serif;
  border-radius: 4px;
  min-height: 36px;
  background: white;
}

.grid-contentss {
  margin-top: 50px;
  font-family: "Microsoft YaHei", Arial, sans-serif;
  border-radius: 4px;
  min-height: 36px;
  background: white;
}

.rounded-input :deep(.el-input__wrapper) {
  border-radius: 15px 0px 0px 15px;
}

.rounded-search {
  border-radius: 0 15px 15px 0;
  background: #FF4400;
}

.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: white;
  color: var(--el-color-primary);
}

.el-slider {
  margin-top: 20px;
}

.button-container .custom-button {
  width: 100%;
  height: 50px;
  background: white;
  color: #409eff;
  border-color: #409eff;
}

.button-container .el-button {
  width: 100%;
  height: 50px;
  background: white;
}

.image-gallery {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background: white;
}

.image-container {
  display: flex;
  gap: 20px;
  height: 450px;
}

.thumbnail-container {
  width: 100px;
  flex-shrink: 0;
}

.thumbnail-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.thumbnail {
  width: 100px;
  height: 100px;
  cursor: pointer;
  border: 2px solid transparent;
  border-radius: 4px;
  transition: border-color 0.3s;
  flex-shrink: 0;
}

.thumbnail.active {
  border-color: #409eff;
}

.thumbnail:hover {
  border-color: #66b1ff;
}

.large-image-container {
  flex: 1;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #eee;
  border-radius: 8px;
  background-color: white;
}

.empty-state {
  color: #999;
  font-size: 16px;
}

.price-info {
  display: inline-flex;
  align-items: center;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  color: #333;
  line-height: 1;
  background: white;
}

.price-before {
  text-decoration: line-through;
  color: #999;
  font-size: 14px;
  margin-right: 6px;
}

.price-after {
  color: #ff4d4f;
  font-size: 16px;
  font-weight: 700;
  margin-right: 8px;
}

.sales {
  font-size: 12px;
  color: #666;
}

.product-options {
  margin-bottom: 30px;
  padding: 15px;
  background-color: white;
  border-radius: 6px;
}

.option-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #333;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}

.color-options {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.color-option {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: white;
}

.color-option:hover {
  border-color: #409eff;
  box-shadow: 0 2px 5px rgba(64, 158, 255, 0.1);
  transform: translateY(-2px);
}

.el-radio__input.is-checked + .color-option {
  border-color: #409eff;
  background-color: white;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.color-img {
  width: 50px;
  height: 50px;
  margin-right: 10px;
  vertical-align: middle;
  border-radius: 4px;
}

.color-img-placeholder {
  width: 50px;
  height: 50px;
  background-color: #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  border-radius: 4px;
}

.color-name {
  vertical-align: middle;
}

.product-actions {
  display: flex;
  gap: 15px;
  padding: 20px 0;
  background: white;
  border-radius: 8px;
  flex-shrink: 0;
  position: sticky;
  bottom: 0;
  z-index: 10;
}

.action-btn {
  flex: 1;
  min-width: 120px;
  height: 50px;
  font-size: 16px;
  font-weight: 500;
}

.add-to-cart-btn {
  background-color: #FFA500;
  border-color: #FFA500;
}

.buy-with-coupon-btn {
  background-color: #FF4500;
  border-color: #FF4500;
}

.collect-btn {
  flex: 0 0 50px;
  background-color: transparent;
  color: #FFA500;
  border-color: transparent;
}

.collect-btn:hover {
  color: #FF4500;
}
</style>
